package com.moli.iov.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moli.iov.base.constants.DictConstants;
import com.moli.iov.base.mapper.TboxUpgradeFileMapper;
import com.moli.iov.base.model.TboxUpgradeFileParam;
import com.moli.iov.base.model.dto.req.SoftVersionReqDto;
import com.moli.iov.base.model.dto.req.TboxUpgradeFileReqDto;
import com.moli.iov.base.model.dto.req.UpgradeFileQueryDto;
import com.moli.iov.base.model.dto.res.TboxUpgradeFileResDto;
import com.moli.iov.base.model.po.DictData;
import com.moli.iov.base.model.po.TboxUpgradeFile;
import com.moli.iov.base.model.po.VehicleBase;
import com.moli.iov.base.service.IDictDataService;
import com.moli.iov.base.service.ITboxUpgradeFileService;
import com.moli.iov.base.util.CollectionUtils;
import com.moli.iov.enums.UserTypeEnum;
import com.moli.iov.exception.BusinessException;
import com.moli.iov.model.dto.req.PageExtend;
import com.moli.iov.rest.RestResponse;
import com.moli.iov.util.CommonUtils;
import com.moli.iov.util.StringUtil;
import com.moli.iov.util.ValidationUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


/**
 * The type Tbox upgrade file service.
 *
 * @author wanghualin
 * @date 2019 -10-09 15:51:28
 */
@Service
public class TboxUpgradeFileServiceImpl extends
        ServiceImpl<TboxUpgradeFileMapper, TboxUpgradeFile> implements ITboxUpgradeFileService {

    private Logger logger = LoggerFactory.getLogger(TboxUpgradeFileServiceImpl.class);
    @Autowired
    private IDictDataService dictDataService;


    @Override
    public List<TboxUpgradeFile> queryAll() {
        QueryWrapper<TboxUpgradeFile> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 0);
        return list(queryWrapper);
    }

    @Override
    public RestResponse saveUpgradeFile(TboxUpgradeFile tboxUpgradeFile) {
        boolean save = save(tboxUpgradeFile);
        return save ? RestResponse.success() : RestResponse.failure("操作失败");
    }

    @Override
    public RestResponse updateUpgradeFile(TboxUpgradeFile byId) {
        boolean update = saveOrUpdate(byId);
        return update ? RestResponse.success() : RestResponse.failure("操作失败");
    }

    @Override
    public RestResponse deleteUpgradeFile(TboxUpgradeFile byId) {
        boolean delete = saveOrUpdate(byId);
        return delete ? RestResponse.success() : RestResponse.failure("操作失败");
    }

    @Override
    public PageExtend<TboxUpgradeFileResDto> listTboxUpgradeFile(UpgradeFileQueryDto reqDto) {
        ValidationUtils.validateBean(reqDto);
        TboxUpgradeFileParam param = new TboxUpgradeFileParam();
        if (reqDto.getSysUserType().intValue() == UserTypeEnum.COMPANY.getFlag()) {
            throw new BusinessException("没有权限");
        }
        param.queryEqCompanyId(reqDto.getCompanyId());
        IPage<TboxUpgradeFile> page = new Page(reqDto.getPageNum(), reqDto.getPageSize());
        IPage<TboxUpgradeFile> list = super.page(page, param.get());
        return assembleTboxUpgradeFileResDto(list);
    }

    @Override
    public TboxUpgradeFile getUpgradeFile(TboxUpgradeFileReqDto reqDto) {
        ValidationUtils.validateBean(reqDto);
        TboxUpgradeFileParam param = new TboxUpgradeFileParam();
        param.queryEqCompanyId(reqDto.getCompanyId());
        param.queryEqSoftwareVersion(reqDto.getSoftwareVersion());
        param.queryEqTboxManufacturer(reqDto.getTboxManufacturer());
        param.queryEqTboxModel(reqDto.getTboxModel());
        param.queryEqVehicleBand(reqDto.getVehicleBand());
        param.queryEqVehilceSeries(reqDto.getVehilceSeries());
        param.queryEqVehicleStyle(reqDto.getVehicleStyle());
        return this.getOne(param.get(), false);
    }

    @Override
    public List<TboxUpgradeFileResDto> listSoftVersion(SoftVersionReqDto reqDto) {
        TboxUpgradeFileParam param = new TboxUpgradeFileParam();
        param.queryEqCompanyId(reqDto.getCompanyId());
        param.queryEqSoftwareVersion(reqDto.getSoftwareVersion());
        param.queryEqTboxManufacturer(reqDto.getTboxManufacturer());
        param.queryEqTboxModel(reqDto.getTboxModel());
        param.queryEqVehicleBand(reqDto.getVehicleBrand());
        param.queryEqVehilceSeries(reqDto.getVehicleSeries());
        param.queryEqVehicleStyle(reqDto.getVehicleType());
        List<TboxUpgradeFile> list = this.list(param.get());
        Set<String> versions = new HashSet<>();
        List<TboxUpgradeFileResDto> resList =new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (TboxUpgradeFile record : list) {
                if (record != null && !StringUtils.isEmpty(record.getSoftwareVersion())) {
                    if(!versions.contains(record.getSoftwareVersion())){
                    TboxUpgradeFileResDto dto = new TboxUpgradeFileResDto();
                    CommonUtils.copyProperties(record, dto);
//        dto.setVehicleModelStr(getVehicleModel(record));
                    resList.add(dto);
                    versions.add(record.getSoftwareVersion());
                    }
                }
            }
        }
        return resList;
    }

    private PageExtend<TboxUpgradeFileResDto> assembleTboxUpgradeFileResDto(IPage<TboxUpgradeFile> list) {
        if (list != null && !CollectionUtils.isEmpty(list.getRecords())) {
            PageExtend<TboxUpgradeFileResDto> res = new PageExtend<>();
            res.setPageSize(list.getSize());
            res.setTotal(list.getTotal());
            res.setPageNumber(list.getCurrent());
            List<TboxUpgradeFileResDto> resDtos = new ArrayList<>();
            for (TboxUpgradeFile record : list.getRecords()) {
                TboxUpgradeFileResDto dto = new TboxUpgradeFileResDto();
                CommonUtils.copyProperties(record, dto);
                if(dto!=null && !StringUtils.isEmpty(dto.getFileUrl()) && dto.getFileUrl().lastIndexOf("/")>-1){
                    String fileUrl = dto.getFileUrl().substring((dto.getFileUrl().lastIndexOf("/")+1));
                    dto.setFileUrl(fileUrl);
                }
                dto.setVehicleModelStr(getVehicleModel(record));
                resDtos.add(dto);
            }
            res.setRecords(resDtos);
            return res;
        }
        return new PageExtend<>();

    }

    /**
     * 返回车辆型号
     */
    public String getVehicleModel(TboxUpgradeFile record) {
        if (record != null &&
                record.getVehicleBand() != null &&
                record.getVehilceSeries() != null &&
                record.getVehicleStyle() != null) {
            StringBuffer sb = new StringBuffer();
            sb.append(getDictValue(DictConstants.DICT_TYPE_VEHICLE_BRAND, record.getVehicleBand()));
            sb.append(getDictValue(DictConstants.DICT_TYPE_VEHICLE_BRAND_SERIES,
                    record.getVehilceSeries()));
            sb.append(getDictValue(DictConstants.DICT_TYPE_VEHICLE_TYPE, record.getVehicleStyle()));
            return sb.toString().contains("null") ? null : sb.toString();
        } else {
            return null;
        }
    }

    /**
     * 获得
     */
    public String getDictValue(String dictType, String dictCode) {
        QueryWrapper<DictData> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_code", dictCode);
        queryWrapper.eq("dict_type", dictType);
        DictData one = dictDataService.getOne(queryWrapper);
        if (one != null) {
            return one.getDictValue();
        }
        return null;
    }
}
